// Sprite definitions and animations
export const SPRITE_SIZE = 64;
export const ANIMATION_SPEED = 150; // ms per frame

export const DIRECTIONS = {
    DOWN: 0,
    LEFT: 1,
    RIGHT: 2,
    UP: 3
};

export class Sprite {
    constructor(image, frameWidth, frameHeight, frameCount, row = 0) {
        this.image = image;
        this.frameWidth = frameWidth;
        this.frameHeight = frameHeight;
        this.frameCount = frameCount;
        this.row = row;
        this.currentFrame = 0;
        this.lastFrameTime = 0;
    }

    update(timestamp) {
        if (timestamp - this.lastFrameTime > ANIMATION_SPEED) {
            this.currentFrame = (this.currentFrame + 1) % this.frameCount;
            this.lastFrameTime = timestamp;
        }
    }

    draw(ctx, x, y, direction = DIRECTIONS.DOWN) {
        ctx.drawImage(
            this.image,
            this.currentFrame * this.frameWidth,
            (direction + this.row) * this.frameHeight,
            this.frameWidth,
            this.frameHeight,
            x - this.frameWidth / 2,
            y - this.frameHeight / 2,
            this.frameWidth,
            this.frameHeight
        );
    }
}

// Load all game sprites
export const loadSprites = async () => {
    const sprites = {
        player: new Image(),
        monsters: {
            slime: new Image(),
            skeleton: new Image(),
            orc: new Image(),
            dragon: new Image()
        },
        items: {
            weapons: new Image(),
            armor: new Image(),
            potions: new Image()
        },
        effects: {
            slash: new Image(),
            magic: new Image(),
            heal: new Image()
        },
        tiles: new Image()
    };

    // Set source paths for all images
    sprites.player.src = 'assets/player.png';
    sprites.monsters.slime.src = 'assets/monsters/slime.png';
    sprites.monsters.skeleton.src = 'assets/monsters/skeleton.png';
    sprites.monsters.orc.src = 'assets/monsters/orc.png';
    sprites.monsters.dragon.src = 'assets/monsters/dragon.png';
    sprites.items.weapons.src = 'assets/items/weapons.png';
    sprites.items.armor.src = 'assets/items/armor.png';
    sprites.items.potions.src = 'assets/items/potions.png';
    sprites.effects.slash.src = 'assets/effects/slash.png';
    sprites.effects.magic.src = 'assets/effects/magic.png';
    sprites.effects.heal.src = 'assets/effects/heal.png';
    sprites.tiles.src = 'assets/tiles.png';

    // Wait for all images to load
    const loadPromises = [
        sprites.player,
        ...Object.values(sprites.monsters),
        ...Object.values(sprites.items),
        ...Object.values(sprites.effects),
        sprites.tiles
    ].map(img => new Promise(resolve => {
        img.onload = resolve;
    }));

    await Promise.all(loadPromises);
    return sprites;
};


